<template>
  <div class="page">
    <div class="store">
      <div class="message">请确认门店：</div>
      <div class="name">丑巧婆牛肉冒菜</div>
      <div class="distance">距离 1km</div>
    </div>
    <div class="menu-panel">
      <div
        class="sidebar"
        :style="{ height: routerViewHeight - 43 - 50 + 'px' }"
      >
        <Sidebar v-model="active" @change="onChange">
          <SidebarItem
            :title="item.name"
            v-for="item in labels"
            :key="item.id"
          />
        </Sidebar>
      </div>
      <div
        class="food-list"
        :style="{ height: routerViewHeight - 43 - 50 + 'px' }"
      >
        <div :ref="'sticky' + index" v-for="(item, index) in shopList">
          <!-- 头吸附在顶部 -->
          <!-- <Sticky :container="getStickyEl(index)">
            <van-button type="warning">指定容器</van-button>
          </Sticky> -->
          <div class="label-panel" :id="'labelAnchor' + item.labelId">
            <div class="label-item">
              <div class="label-name">{{ item.name }}</div>
              <div class="label-message">{{ item.message }}</div>
            </div>
          </div>
          <div class="shop-list">
            <div v-for="shop in item.cihldren" :key="shop.id">
              <div
                :class="['shop-children', shop.inventory == 0 ? 'mask' : '']"
              >
                <Image
                  style="position: absolute; right: 0; top: 25%"
                  v-if="shop.inventory == 0"
                  width="4rem"
                  height="4rem"
                  fit="cover"
                  position="center"
                  :src="require('@/assets/soldOut.png')"
                />
                <div class="shop-img">
                  <Image
                    width="4rem"
                    height="4rem"
                    fit="cover"
                    position="center"
                    :src="baseApi + shop.img"
                  />
                </div>
                <div class="shop-content">
                  <div class="name">
                    {{ shop.name }}
                  </div>
                  <div class="message">
                    <TextEllipsis :content="shop.message" :rows="2" />
                  </div>
                  <div class="opera-group">
                    <div class="price-group">
                      <span class="price">{{ shop.price }}</span>
                      <span class="scrib-price">{{ shop.scribPrice }}</span>
                    </div>
                    <div class="shop-cart-add" v-if="!shop.inventory == 0">
                      <Icon
                        name="add"
                        v-if="
                          !Object.keys(shoppingCart).some(
                            (item) => Number(item) == shop.id
                          )
                        "
                        @click="addShoppingCart(shop)"
                      />
                      <Stepper
                        theme="round"
                        button-size="22"
                        disable-input
                        v-else
                        min="0"
                        @change="changeShoppingCartNumber(shop.id)"
                        v-model="shoppingCart[shop.id]"
                        integer
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹出购物车 -->
    <Popup
      v-model:show="showShoppingCart"
      position="bottom"
      round
      :style="{ height: '300px', overflow: 'auto' }"
    >
      <!-- 购物车内 -->
      <div class="shopcart-popup">
        <div class="spp-header">购物车</div>
        <div class="spp-clean">
          <Icon name="delete-o"></Icon>
          <span @click="cleanShopppingCart">清空购物车</span>
        </div>
        <div
          v-if="shopData.length === 0 || Object.keys(shoppingCart).length === 0"
        >
          <Empty description="空空如也" style="padding: 0" />
        </div>
        <div class="spp-list" v-else>
          <div
            v-for="shopId in Object.keys(shoppingCart).map(Number)"
            :key="shopId"
          >
            <div class="spp-item">
              <div class="shop-img">
                <Image
                  width="4rem"
                  height="4rem"
                  fit="cover"
                  position="center"
                  :src="baseApi + getShopById(shopId).img"
                />
              </div>
              <div class="content">
                <div class="name">
                  {{ getShopById(shopId).name }}
                </div>
                <div class="message">
                  <TextEllipsis
                    :content="getShopById(shopId).message"
                    :rows="2"
                  />
                </div>
                <div class="opera-group">
                  <div class="price-group">
                    <div class="price-total">
                      {{ getShopById(shopId).price * shoppingCart[shopId] }}
                    </div>
                    <div class="scrib-price-total">
                      {{
                        getShopById(shopId).scribPrice * shoppingCart[shopId]
                      }}
                    </div>
                  </div>
                  <Stepper
                    theme="round"
                    button-size="22"
                    disable-input
                    min="0"
                    @change="changeShoppingCartNumber(shopId)"
                    v-model="shoppingCart[shopId]"
                    integer
                  />
                </div>
              </div>
            </div>
            <Divider :style="{ margin: '10px 0' }" />
          </div>
        </div>
      </div>
    </Popup>
    <!-- 提交栏 -->
    <div class="shop-cart">
      <SubmitBar
        :price="totalPrice"
        :button-text="
          disabledSubmit ? '起送价:¥' + minDeliveryAmount : '提交订单'
        "
        :disabled="disabledSubmit"
        @submit="submitOrder"
      >
        <Badge :content="spCartTotal" max="99" :show-zero="false">
          <Button
            @click="showShoppingCart = true"
            icon="shop-collect"
            type="primary"
            round
            color="linear-gradient(to right, #ff6034, #ee0a24)"
          />
        </Badge>
      </SubmitBar>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, inject, watch, computed, reactive, onMounted } from "vue";
import {
  Sidebar,
  SidebarItem,
  SubmitBar,
  Popup,
  Image,
  Icon,
  Stepper,
  Button,
  Badge,
  Empty,
  Divider,
  TextEllipsis,
  showFailToast,
} from "vant";
import { selectShopAll, selectShopLabelAll } from "@/api/shop";
import { getConfigKey } from "@/api/system/config";
import enums from "@/utils/enums";
import router from "@/router";
import {
  getLocalStorage,
  removeLocalStorage,
  setLocalStorage,
} from "@/utils/auth";

// 变量

// 页面高度
const routerViewHeight: number = inject("routerViewHeight")!;
// 左边标签默认选中第一个
const active = ref(0);
//左边标签列表
const labels = ref([]);

//右边商品列表
const shopData = ref([]);

/**起送价 */
const minDeliveryAmount = ref(999);

/**后端api接口 */
const baseApi = process.env.VUE_APP_BASE_API;

/**弹出购物车 */
const showShoppingCart = ref(false);
//购物车
const shoppingCart = ref({});
//金额
const totalPrice = computed(() => {
  let price = 0;
  Object.keys(shoppingCart.value).forEach((shopId) => {
    price +=
      (getShopById(Number(shopId))?.price || 0) * shoppingCart.value[shopId];
  });
  return price * 100;
});
//购物车中的商品数量
const spCartTotal = computed(() => {
  const val = Object.values(shoppingCart.value).reduce(
    (a: any, b: any) => a + b,
    0
  );
  return val ? Number(val) : 0;
});
/**禁止提交订单 */
const disabledSubmit = computed(() => {
  if (minDeliveryAmount.value > totalPrice.value) {
    return true;
  }
});

//方法
onMounted(() => {
  getLabelList();
  getShopList();
  shoppingCart.value =
    JSON.parse(getLocalStorage(enums.localStorage.order.shoppingCart)) || {};
  //获取起送价
  getConfigKey(enums.config.minimum_delivery_amount).then((res: any) => {
    minDeliveryAmount.value = Number(res.msg);
  });
});
/**根据商品id获取商品对象 */
const getShopById = (id: number): any => {
  return shopData.value.find((item: any) => item.id === id);
};

/**查询所有label */
const getLabelList = () => {
  selectShopLabelAll().then((res: any) => {
    labels.value = res.data.sort((a: any, b: any) => a.sortIndex - b.sortIndex);
  });
};
const getShopList = () => {
  selectShopAll().then((res: any) => {
    shopData.value = res.data;
  });
};

/**清空购物车 */
const cleanShopppingCart = () => {
  shoppingCart.value = {};
  removeLocalStorage(enums.localStorage.order.shoppingCart);
};

// 删除购物车
const changeShoppingCartNumber = (shopId: number) => {
  if (shoppingCart.value[shopId] === 0) {
    delete shoppingCart.value[shopId];
  }
  setLocalStorage(
    enums.localStorage.order.shoppingCart,
    JSON.stringify(shoppingCart.value)
  );
};

//添加购物车
const addShoppingCart = (shop: any) => {
  if (Object.keys(shoppingCart.value).some((id) => id === shop.id)) {
    shoppingCart.value[shop.id] = shoppingCart.value[shop.id] + 1;
  } else {
    shoppingCart.value[shop.id] = 1;
  }
  setLocalStorage(
    enums.localStorage.order.shoppingCart,
    JSON.stringify(shoppingCart.value)
  );
};

// 标签切换事件
const onChange = (index: number) => {
  document
    .querySelector("#labelAnchor" + labels[index].id)
    ?.scrollIntoView({ behavior: "smooth", block: "start" });
};

//标签和商品列表改成更方便的结构
const shopList = computed(() => {
  return labels.value.map((label: any) => {
    return {
      labelId: label.id,
      name: label.name,
      message: label.message,
      cihldren:
        shopData.value.filter((shop: any) => shop.labelId === label.id) || [],
    };
  });
});
/**提交订单 */
const submitOrder = () => {
  if (totalPrice >= minDeliveryAmount) {
    setLocalStorage("shoppingCart", JSON.stringify(shoppingCart.value));
    router.push("/orderMeal/submit");
  }
};
</script>
<!-- 购物车内 -->
<style lang="less" scoped>
.shopcart-popup {
  box-sizing: border-box;
  .spp-header {
    background: linear-gradient(to right, #ff6034, #ee0a24);
    color: white;
    text-align: center;
    font-size: 12px;
    padding: 8px;
  }
  .spp-clean {
    padding: 16px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 12px;
    color: #999;
  }
  .spp-list {
    padding: 0 16px;
    display: flex;
    flex-direction: column;
    .spp-item {
      width: 100%;
      box-sizing: border-box;
      display: flex;
      gap: 10px;
      .shop-img {
        /deep/img {
          border-radius: 16px;
        }
      }
      .content {
        flex: 1;
        .name {
          font-weight: 600;
          font-size: 16px;
          color: #333;
        }
        .message {
          font-size: 12px;
          color: #999;
        }
        .opera-group {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          .price-group {
            display: flex;
            align-items: flex-end;
            .price-total::before {
              content: "¥";
              font-size: 12px;
            }
            .scrib-price-total::before {
              content: "¥";
            }
            .price-total {
              font-size: 20px;
              font-weight: 600;
              color: #ff5339;
              margin-right: 5px;
            }
            .scrib-price-total {
              font-size: 12px;
              font-weight: 400;
              color: #999;
              text-decoration: line-through;
            }
          }
        }
      }
    }
  }
}
</style>
<style lang="less" scoped>
.food-list {
  .label-panel {
    padding: 10px 10px 0px 10px;
    background-color: #fff;
    border-radius: 5px;
    .label-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .label-name {
        font-size: 14px;
        font-weight: 600;
        color: #333;
      }
      .label-message {
        font-size: 12px;
        color: #999;
      }
    }
  }
  .shop-list {
    .shop-children {
      border-radius: 5px;
      padding: 5px 10px;
      background-color: #fff;
      border-bottom: 1px solid #f5f5f5;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 10px;
      .shop-content {
        .name {
          font-size: 14px;
          font-weight: 600;
          color: #333;
        }
        .message {
          font-size: 12px;
          font-weight: 400;
          color: #999;
        }
        .opera-group {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .price-group {
            .price::before {
              content: "¥";
              font-size: 12px;
            }
            .scrib-price::before {
              content: "¥";
            }
            .price {
              font-size: 20px;
              font-weight: 600;
              color: #ff5339;
              margin-right: 5px;
            }
            .scrib-price {
              font-size: 12px;
              font-weight: 400;
              color: #999;
              text-decoration: line-through;
            }
          }
        }
      }
      .shop-img {
        /deep/.van-image__img {
          border-radius: 5px;
        }
      }
      .shop-content {
        flex: 1;
      }
      .shop-cart-add {
        color: #ee0a24;
        font-size: 1.5rem;
      }
    }
  }
}
.shop-cart {
  .van-submit-bar {
    position: absolute;
    bottom: var(--van-tabbar-height);
  }
}
.menu-panel {
  display: flex;
  justify-content: flex-start;
  .sidebar {
    overflow: auto;
    width: var(--van-sidebar-width);
    background: #ffffff;
    /deep/.van-sidebar-item {
      background-color: #ffffff;
    }
    /deep/.van-sidebar-item--select {
      background-color: var(--van-sidebar-background);
    }
  }
  .food-list {
    flex: 1;
    padding: 10px;
    box-sizing: border-box;
    overflow: auto;
    background: var(--van-sidebar-background);
  }
}
.store {
  height: 43px;
  display: flex;
  justify-content: space-between;
  padding: 0 15px;
  align-items: center;
  .name {
    font-size: 16px;
    font-weight: 700;
  }
  .distance {
    color: #999;
    font-size: 12px;
  }
  .message {
    color: #999;
    font-size: 12px;
  }
}
</style>

<style lang="less" scoped>
.mask {
  position: relative;
  background-color: black;
  opacity: 0.4;
  filter: alpha(opacity=10);
  z-index: 100;
}
</style>
